import pymysql
from dbutils.pooled_db import PooledDB
import redis
from config.db import MySql, RedisConfig


# conn = dbpool.connection()
# cur = conn.cursor()
# SQL = 'select * from yugong_user;'
# cur.execute(SQL)
# f = cur.fetchall()
# print(f)
# cur.close()
# conn.close()

class Cursor:
    db_config = {
        'host': MySql.host,
        'port': MySql.port,
        'user': MySql.user,
        'passwd': MySql.password,
        'db': 'yugong_blog',
        'charset': 'utf8mb4',
        'maxconnections': 20,  # 连接池允许的最大连接数
        'mincached': 10,  # 初始化时连接池中至少创建的空闲的连接，0表示不创建
        'maxcached': 10,  # 连接池中最多闲置的连接，0表示不限制，连接使用完成后的空闲连接保留数。
        'maxusage': 100,  # 每个连接最多被重复使用的次数，None表示不限制
        'blocking': True,  # 连接池中如果没有可用连接后是否阻塞等待，
    }
    # dbpool = PooledDB(pymysql, **db_config, setsession=['SET AUTOCOMMIT = 1'])
    dbpool = PooledDB(pymysql, **db_config)


    def __init__(self):
        self.conn = None
        self.cursor = None

    def __enter__(self):
        self.conn = self.dbpool.connection()
        self.conn.begin()
        self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
        return self.cursor

    def __exit__(self, exc_type, exc_value, exc_tb):
        if not exc_type:
            self.conn.commit()
        else:
            print(exc_type, exc_value)
            self.conn.rollback()
        self.cursor.close()
        self.conn.close()


class RedisCursor:

    def __init__(self):
        self.conn = None

    def __enter__(self):
        self.conn = redis.StrictRedis(host=RedisConfig.host, port=RedisConfig.port, db=0)
        return self.conn

    def __exit__(self, exc_type, exc_value, exc_tb):
        if exc_type:
            print(exc_type)
        self.conn.close()



